package com.lanou.musicproject.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.musicproject.R;
import com.lanou.musicproject.adapter.SeekGridViewAdapter;
import com.lanou.musicproject.adapter.SeekListAdapter;
import com.lanou.musicproject.base.BaseActivity;
import com.lanou.musicproject.bean.SearchSongEntity;
import com.lanou.musicproject.bean.Seek;
import com.lanou.musicproject.bean.Singer;
import com.lanou.musicproject.bean.SongSearch;
import com.lanou.musicproject.tools.FormatCodeUtil;
import com.lanou.musicproject.volley.VolleySingleton;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/10/22.
 */
public class SeekActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private String url, urls, songUrl;
    private List<Seek.DataEntity> data;
    private SeekGridViewAdapter adapter;
    private SeekListAdapter listadapter;
    private ArrayList<SearchSongEntity> datas; //实体类
    private VolleySingleton volleySingleton;
    private EditText seek_edit;
    private ImageView seek_image;
    private GridView gridView;
    private ListView songSearchLV;
    Handler myhandler = new Handler();//开启新线程

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seek_activity);
        seek_edit = (EditText) findViewById(R.id.seek_edit);
        seek_image = (ImageView) findViewById(R.id.seek_image);
        gridView = (GridView) findViewById(R.id.seek_gridview);
        songSearchLV = (ListView) findViewById(R.id.songSearchLV);
        gridView.setOnItemClickListener(this);
        songSearchLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                seek_edit.setText(datas.get(position).getSongname());
            }
        });
        seek_image.setOnClickListener(this);
        volleySingleton = VolleySingleton.getInstance(this);
        //数据变化

        TextChanged();


        initData();
    }

    private void TextChanged() {
        seek_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //开启线程
                myhandler.post(eChanged);
            }
        });
    }

    Runnable eChanged = new Runnable() {
        @Override
        public void run() {
            //从searchETv组件获得数据
            String text = seek_edit.getText().toString();
            String songUrl = FormatCodeUtil.codingFormat(text);

            //进行网址拼接
            urls = " http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&" +
                    "method=baidu.ting.search.catalogSug&format=json&query=" + songUrl
            ;

            Log.i("lanou000", urls + "");
            //进行网络请求
            StringRequest sr = new StringRequest(urls, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //进行Gson数据解析
                    Gson gson = new Gson();
                    SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    //获得数据
                    datas = songSearch.getSong();
                    //初始化适配器
                    listadapter = new SeekListAdapter(SeekActivity.this, datas);
                    //绑定适配器
                    songSearchLV.setAdapter(listadapter);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(sr);
            if (songUrl != null) {
                gridView.setVisibility(View.GONE);
                songSearchLV.setVisibility(View.VISIBLE);
            } else {
                gridView.setVisibility(View.VISIBLE);
                songSearchLV.setVisibility(View.GONE);
            }
        }
    };


    private void initData() {
        url = "http://api.dongting.com/misc/sug/billboard?" +
                "uid=866058021842951&f=f3040&v=v8.2.0.2015091720&app=ttpod&utdid=VSeGyjss0fEDAOqIktP5W%2BO4" +
                "&hid=1135212123029932&s=s200&alf=alf203200&imsi=460078098497828&tid=0&net=2&size=20";
        JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                String str = response.toString();
                Seek seek = JSON.parseObject(str, Seek.class);
                data = seek.getData();
                adapter = new SeekGridViewAdapter(SeekActivity.this, data);
                gridView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(jr);
        if (songUrl != null) {
            gridView.setVisibility(View.GONE);
            songSearchLV.setVisibility(View.VISIBLE);
        } else {
            gridView.setVisibility(View.VISIBLE);
            songSearchLV.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        String text = seek_edit.getText().toString();
        Log.i("lanou", text);
        if (text.length() <= 0) {
            Toast.makeText(this, "请输入歌名.....", Toast.LENGTH_LONG).show();
        } else {
            try {
                String songUrl = URLEncoder.encode(text, "UTF-8");
                String s = seek_edit.getText().toString();
                Log.i("+++++++++++++>>", "    " + songUrl);
                //跳转到搜索完成页面并传递值
                Intent intent = new Intent(SeekActivity.this, SeekContentActivity.class);
                intent.putExtra("url", songUrl);
                intent.putExtra("seek_title", s);

                startActivity(intent);
                finish();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         switch (parent.getId()){
             case R.id.seek_gridview:
                 Seek.DataEntity entity = (Seek.DataEntity) parent.getItemAtPosition(position);
                 seek_edit.setText(entity.getVal());
                 break;

         }
    }
}
